package com.cskaoyan.service.wxcart;

import com.cskaoyan.bean.goods.Goods;
import com.cskaoyan.bean.goods.GoodsProduct;
import com.cskaoyan.bean.promotion.Coupon;
import com.cskaoyan.bean.promotion.CouponUserExample;
import com.cskaoyan.bean.promotion.GrouponRules;
import com.cskaoyan.bean.user.Address;
import com.cskaoyan.bean.user.WxUserLoginData;
import com.cskaoyan.bean.wxcart.WxCart;
import com.cskaoyan.bean.wxcart.WxCartExample;
import com.cskaoyan.bo.wxcart.WxCartCheckedBo;
import com.cskaoyan.bo.wxcart.WxCartDeleteBo;
import com.cskaoyan.bo.wxcart.WxCartBo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.BigDecimalUtil;
import com.cskaoyan.vo.wxcart.WxCartCheckoutVo;
import com.cskaoyan.vo.wxcart.WxCartFastAddVo;
import com.cskaoyan.vo.wxcart.WxCartIndexVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: mall
 * @description:
 * @author: Mr.Mengmeng
 * @create: 2021-04-13 00:16
 **/
// wx小程序 购物车模块
@Service
public class WxCartServiceImpl implements WxCartService {
    //    static Converter converter=PojoUtils.converter();
    @Autowired
    WxCartMapper wxCartMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    GrouponRulesMapper grouponRulesMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    CouponUserMapper couponUserMapper;

    @Override
    public WxCartIndexVo cartIndex() {


        Subject subject = SecurityUtils.getSubject();
        WxUserLoginData loginData = (WxUserLoginData) subject.getPrincipal();
        Integer userId = loginData.getId();


        // 查看该用户id的购物车
        WxCartExample wxCartExample = new WxCartExample();
        WxCartExample.Criteria criteria = wxCartExample.createCriteria();
        criteria.andDeletedEqualTo(false)
                .andUserIdEqualTo(userId);
        List<WxCart> wxCarts = wxCartMapper.selectByExample(wxCartExample);
        // 统计
        short goodsCount = 0;
        short checkedGoodsCount = 0;
        double goodsAmount = 0;
        double checkedGoodsAmount = 0;
        for (WxCart wxCart : wxCarts) {
            goodsCount += wxCart.getNumber();
            goodsAmount += BigDecimalUtil.mul(wxCart.getPrice().doubleValue(), wxCart.getNumber()).doubleValue();
            // 判断商品是否被选择
            if (wxCart.getChecked()) {
                checkedGoodsCount += wxCart.getNumber();
                checkedGoodsAmount += BigDecimalUtil.mul(wxCart.getPrice().doubleValue(), wxCart.getNumber()).doubleValue();
            }
        }
        WxCartIndexVo.CartTotalBean cartTotalBean = new WxCartIndexVo.CartTotalBean(goodsCount, checkedGoodsCount,
                goodsAmount, checkedGoodsAmount);
        // 返回参数
        return new WxCartIndexVo(cartTotalBean, wxCarts);
    }

    @Override
    public int cartGoodsCount() {
        Subject subject = SecurityUtils.getSubject();
        WxUserLoginData loginData = (WxUserLoginData) subject.getPrincipal();
        Integer userId = loginData.getId();
        // 查看该用户id的购物车
        WxCartExample wxCartExample = new WxCartExample();
        WxCartExample.Criteria criteria = wxCartExample.createCriteria();
        criteria.andDeletedEqualTo(false)
                .andUserIdEqualTo(userId);
        List<WxCart> wxCarts = wxCartMapper.selectByExample(wxCartExample);

//        short goodsCount = 0;
//        for (WxCart wxcart : wxCarts) {
//            goodsCount += wxcart.getNumber();
//        }
        return wxCarts.size();
    }

    @Override
    public void cartDelete(WxCartDeleteBo wxCartDeleteBo) {
        Subject subject = SecurityUtils.getSubject();
        WxUserLoginData loginData = (WxUserLoginData) subject.getPrincipal();
        Integer userId = loginData.getId();
        // 做删除购物车商品的操作
        for (Integer productId : wxCartDeleteBo.getProductIds()) {
            // 根据用户id，商品id找到该商品
            WxCartExample wxCartExample = new WxCartExample();
            WxCartExample.Criteria criteria = wxCartExample.createCriteria();
            criteria.andDeletedEqualTo(false)
                    .andUserIdEqualTo(userId)
                    .andProductIdEqualTo(productId);
            // 逻辑删除
            WxCart wxCart = new WxCart();
            wxCart.setDeleted(true);
            wxCart.setUpdateTime(new Date());
            wxCartMapper.updateByExampleSelective(wxCart, wxCartExample);
        }
    }

    @Override
    public void cartChecked(WxCartCheckedBo bo) {
        Subject subject = SecurityUtils.getSubject();
        WxUserLoginData loginData = (WxUserLoginData) subject.getPrincipal();
        Integer userId = loginData.getId();
        // 做选择商品的操作
        for (Integer productId : bo.getProductIds()) {
            WxCartExample wxCartExample = new WxCartExample();
            WxCartExample.Criteria criteria = wxCartExample.createCriteria();
            criteria.andDeletedEqualTo(false)
                    .andUserIdEqualTo(userId)
                    .andProductIdEqualTo(productId);
            // 设置取消功能
            WxCart wxCart = new WxCart();
            wxCart.setChecked(bo.getIsChecked());
            wxCart.setUpdateTime(new Date());
            wxCartMapper.updateByExampleSelective(wxCart, wxCartExample);
        }
    }

    @Override
    public int cartUpdate(WxCartBo bo) {
        Subject subject = SecurityUtils.getSubject();
        WxUserLoginData loginData = (WxUserLoginData) subject.getPrincipal();
        Integer userId = loginData.getId();

        // 先查询购物车中该商品信息
        WxCart wxCart = wxCartMapper.selectByPrimaryKey(bo.getId());
        // 查询库存信息--> 判断库存
        GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(bo.getProductId());
        if (bo.getNumber() > goodsProduct.getNumber()) {
            // 更新购物车
            wxCart.setNumber(goodsProduct.getNumber().shortValue());
            wxCart.setUpdateTime(new Date());
            wxCartMapper.updateByPrimaryKeySelective(wxCart);
            return 710;
        } else {
            wxCart.setNumber(bo.getNumber());
            wxCart.setUpdateTime(new Date());
            wxCartMapper.updateByPrimaryKeySelective(wxCart);
            return 0;
        }
    }

    @Override
    public WxCartFastAddVo cartAdd(WxCartBo bo) {
        Subject subject = SecurityUtils.getSubject();
        WxUserLoginData loginData = (WxUserLoginData) subject.getPrincipal();
        Integer userId = loginData.getId();

        // 商品信息
        Goods goods = goodsMapper.selectByPrimaryKey(bo.getGoodsId());
        // 商品规格的信息
        GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(bo.getProductId());
        // 判断是否有相同参数的商品
        WxCartExample wxCartExample = new WxCartExample();
        WxCartExample.Criteria criteria = wxCartExample.createCriteria();
        criteria.andDeletedEqualTo(false)
                .andUserIdEqualTo(userId)
                .andGoodsIdEqualTo(bo.getGoodsId())
                .andProductIdEqualTo(bo.getProductId());
        List<WxCart> wxCarts = wxCartMapper.selectByExample(wxCartExample);
        WxCart wxCart;
        // 没有相同
        if (wxCarts.size() == 0) {
            // 判断库存
            if (bo.getNumber() > goodsProduct.getNumber()) {
                return new WxCartFastAddVo(710, null);
            } else {
                wxCart = new WxCart(null, userId, bo.getGoodsId(), goods.getGoodsSn(), goods.getName(),
                        bo.getProductId(), goodsProduct.getPrice(), bo.getNumber(), goodsProduct.getSpecifications(),
                        true, goodsProduct.getUrl(), new Date(), new Date(), false);
                // 添加操作
                wxCartMapper.insertSelective(wxCart);
                return new WxCartFastAddVo(0, wxCart.getId());
            }
        } else {
            wxCart = wxCarts.get(0);
            // 有相同
            // 判断库存
            if (wxCart.getNumber() + bo.getNumber() > goodsProduct.getNumber()) {
                return new WxCartFastAddVo(710, null);
            } else {
                wxCart.setNumber((short) (wxCart.getNumber() + bo.getNumber()));
                wxCart.setChecked(true);
                wxCart.setUpdateTime(new Date());
                // 添加操作
                wxCartMapper.updateByPrimaryKeySelective(wxCart);
                return new WxCartFastAddVo(0, wxCart.getId());
            }
        }

    }

    @Override
    public WxCartCheckoutVo cartCheckout(Integer cartId, Integer addressId, Integer couponId, Integer grouponRulesId) {
        Subject subject = SecurityUtils.getSubject();
        WxUserLoginData loginData = (WxUserLoginData) subject.getPrincipal();
        Integer userId = loginData.getId();
        // TODO: 假设团购id为1,假设优惠卷id为1
        grouponRulesId = 1;
        // couponId=1;

        // 查找团购信息
        GrouponRules grouponRules = grouponRulesMapper.selectByPrimaryKey(grouponRulesId);
        BigDecimal grouponPrice = BigDecimal.valueOf(0);// 团购价格
        // TODO: 如果没过期和人数够了
        Date date = new Date();
        if (date.after(grouponRules.getExpireTime())) {
            grouponPrice = grouponRules.getDiscount();// 团购优惠价格
        }
        // 查找优惠卷信息
        BigDecimal couponPrice;// 优惠卷价格
        Integer availableCouponLength = 0;// 优惠卷数量
        Coupon coupon = new Coupon();
        if (couponId == 0 || couponId == -1) {
            couponPrice = BigDecimal.valueOf(0);// 优惠卷价格
            CouponUserExample couponUserExample = new CouponUserExample();
            CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
            criteria.andUserIdEqualTo(userId).andStatusEqualTo((short)0).andDeletedEqualTo(false);

            List<Integer> couponIds = couponUserMapper.selectCouponIdsByExample(couponUserExample);
            availableCouponLength = couponIds.size();// 优惠卷数量
        } else {
            coupon = couponMapper.selectByPrimaryKey(couponId);
            couponPrice = coupon.getDiscount();
        }

        // 查找地址信息
        Address address = addressMapper.selectByPrimaryKey(addressId);

        // 获取全部商品信息


        double goodsTotalPrice = 0;// 商品总费用
        Integer freightPrice = 8;// 运费
        double orderTotalPrice;// 订单全部价格=商品价格+运费-优惠卷
        double actualPrice;// 实际价格=订单价格-用户积分
        double userScore = 0;// 用户积分
        List<WxCart> checkedGoodsList;// 商品list详情

        // 这里需要区别是否是fastadd(cartId不为0就是fastadd，为0就是正常结算)
        if (cartId != 0) {
            WxCart wxCart = wxCartMapper.selectByPrimaryKey(cartId);
            goodsTotalPrice = wxCart.getPrice().doubleValue() * wxCart.getNumber();
            if (goodsTotalPrice >= 88) {
                freightPrice = 0; // 运费满88减8
            }
            if (coupon.getMin() != null) {
                if (goodsTotalPrice >= coupon.getMin().doubleValue()) {
                    couponPrice = coupon.getDiscount(); // 优惠卷减免
                }
            }

            orderTotalPrice = goodsTotalPrice + freightPrice - couponPrice.doubleValue();
            actualPrice = orderTotalPrice - userScore;

            checkedGoodsList = new ArrayList<>();
            checkedGoodsList.add(wxCart);
            // 返回值
            return new WxCartCheckoutVo(grouponPrice, grouponRulesId,
                    couponId, couponPrice, availableCouponLength, addressId, address,
                    goodsTotalPrice, freightPrice, orderTotalPrice, actualPrice, checkedGoodsList);
        } else {
            // 获取订单所有商品
            WxCartExample wxCartExample = new WxCartExample();
            WxCartExample.Criteria criteria = wxCartExample.createCriteria();
            criteria.andDeletedEqualTo(false)
                    .andUserIdEqualTo(userId)
                    .andCheckedEqualTo(true);
            List<WxCart> wxCarts = wxCartMapper.selectByExample(wxCartExample);
            for (WxCart wxCart : wxCarts) {
                goodsTotalPrice += wxCart.getPrice().doubleValue() * wxCart.getNumber();
            }
            if (goodsTotalPrice >= 88) {
                freightPrice = 0; // 运费满88减8
            }
            if (coupon.getMin() != null) {
                if (goodsTotalPrice >= coupon.getMin().doubleValue()) {
                    couponPrice = coupon.getDiscount(); // 优惠卷减免
                }
            }
            orderTotalPrice = goodsTotalPrice + freightPrice - couponPrice.doubleValue();
            actualPrice = orderTotalPrice - userScore;

            checkedGoodsList = wxCarts;
            return new WxCartCheckoutVo(grouponPrice, grouponRulesId,
                    couponId, couponPrice, availableCouponLength, addressId, address,
                    goodsTotalPrice, freightPrice, orderTotalPrice, actualPrice, checkedGoodsList);
        }
    }

}
